<script setup lang="ts">
definePageMeta({
  layout: false,
  validate: async (route) => {
    return (
      typeof route.params.url === "string" &&
      /^[a-zA-Z0-9]{5,6}$/.test(route.params.url) &&
      !route.params.url.startsWith("/user") &&
      !route.params.url.startsWith("/admin") &&
      !route.params.url.startsWith("/auth")
    );
  },
});

const { url } = useRoute().params;
const { $get, $post } = use$fetch();
const { isLoading } = useStatus();
const urlData = ref<ApiUrl | null>(null);
const showPwd = ref(false);
const frm = reactive({ password: "" });

const gotoOrigin = (origin: string) => {
  if (window) {
    window.location.href = origin;
  }
};

const loadData = async () => {
  await $get<ApiUrl>(`/visit/${url}`, (v) => {
    if (v && !v.has_password) {
      gotoOrigin(v.origin);
      return v;
    }
    urlData.value = v;
    return v;
  });
};

const handleSubmit = async () => {
  await $post<BoolResp>(
    `/visit/${urlData.value?.id}/check-pwd`,
    {
      id: urlData.value?.id,
      password: frm.password,
    },
    (v) => {
      if (v && v.result) {
        isLoading.value = true;
        gotoOrigin(urlData.value?.origin!);
        return v;
      }
      return v;
    }
  );
};

await loadData();
</script>

<template>
  <ClientOnly
    ><div>
      <form
        v-if="urlData && urlData.has_password"
        @submit.prevent="handleSubmit"
        class="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-white p-6 border rounded-md shadow-md flex flex-col items-start gap-y-6 w-4/5 lg:w-1/5"
      >
        <label class="flex flex-col gap-y-4 w-full">
          <div class="">请输入访问密码</div>
          <div
            class="flex justify-end items-center border rounded px-3 py-1.5 w-full border-gray-200 focus-within:border-gray-300"
          >
            <div class="grow">
              <input
                class="bg-transparent block w-full outline-none"
                required
                :type="showPwd ? 'text' : 'password'"
                v-model="frm.password"
              />
            </div>
            <div class="shrink-0 cursor-pointer" @click="showPwd = !showPwd">
              <Icon v-if="!showPwd" name="uil:eye" />
              <Icon v-else name="uil:eye-slash" />
            </div>
          </div>
        </label>

        <div class="w-full flex flex-col items-end">
          <button
            type="submit"
            class="bg-cyan-700 text-white px-4 py-1.5 border rounded hover:bg-cyan-800"
          >
            提交
          </button>
        </div>
      </form>

      <div
        v-else
        class="fixed left-1/2 top-10 -translate-x-1/2 bg-white p-6 border rounded-md shadow-md flex flex-col items-start gap-y-6"
      >
        正在跳转，请稍候…
      </div>
    </div></ClientOnly
  >
</template>
